/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dailynewsreader.view;

import dailynewsreader.model.LabelStorage;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

/**
 * Az rss feedk-eket reprezentáló GUI elem
 * @author Várhegyi Tamás
 */
public class RSSFeed extends JPanel{
    
    /**
     * Kedvencnek jelölő gomb
     */
    private JButton favoriteButton;
    
    /**
     * Leiratkozás gomb
     */
    private JButton unsubscribeButton;
    
    /**
     * Tartalmat kezelő objektum
     */
    private JEditorPane container;  
    
    /**
     * Html stílus beállítások
     */
    private String htmlStyle;
    
    /**
     * RSS feed címe
     */
    private String title;  
    
    /**
     * RSS feed logó url
     */
    private String logoURL;
    
    /**
     * Kedvencnek jelölt-e a feed
     */
    private boolean isFavorite;
    
    /**
     * A feed-et tartalmazó panel
     */
    private RSSReaderPanel panel;
    
    /**
     * RSSFeed konstruktora
     * @param panel A feed-et tartalmazó panel
     */
    public RSSFeed(RSSReaderPanel panel) {
        this.panel = panel;
        initComponents();
    }
    
    /**
     * A cím beállítása
     * @param title Cím
     */
    public void setTitle(String title){
        this.title = title;
    }
    
    /**
     * Kedvencnek beállítás
     * @param isFavorite Kedvenc-e
     */
    public void setIsFavorite(boolean isFavorite){
        this.isFavorite = isFavorite;
        switchFavoriteButtonIcon();
    }
    
    /**
     * A kedvencnek jelölő gomb iconjának változtatás
     * attól függően, hogy kedvenc-e a feed
     */
    private void switchFavoriteButtonIcon(){
        ImageIcon ico;         
        if (isFavorite) {
            String pathToIcon = "dailynewsreader/resources/dnr_fav_on.png";
            ico = new ImageIcon(getClass().getClassLoader().getResource(pathToIcon));            
        } 
        else {
            String pathToIcon = "dailynewsreader/resources/dnr_fav_off.png";
            ico = new ImageIcon(getClass().getClassLoader().getResource(pathToIcon));
        } 
        
        Image icon = ico.getImage();
        Image resizedIcon = icon.getScaledInstance(24, 24,  java.awt.Image.SCALE_SMOOTH ) ;
        ico = new ImageIcon(resizedIcon);
        favoriteButton.setIcon(ico);
    }
    
    /**
     * A GUI feeden a gombok láthatóságát állítja
     * @param visible 
     */
    public void setButtons(boolean visible){
        favoriteButton.setVisible(visible);
        unsubscribeButton.setVisible(visible);
    }
    
    /**
     * GUI komponensek inicializálása
     */
    private void initComponents(){
        container = new JEditorPane();         
        setBackground(Color.white);
        container.setContentType("text/html");
        container.setEditable(false);
        
        String pathToIcon = "dailynewsreader/resources/dnr_fav_off.png";
        ImageIcon ico = new ImageIcon(getClass().getClassLoader().getResource(pathToIcon));
        Image icon = ico.getImage();
        Image resizedIcon = icon.getScaledInstance(24, 24,  java.awt.Image.SCALE_SMOOTH ) ;
        ico = new ImageIcon(resizedIcon);
        favoriteButton = new JButton(ico);
        favoriteButton.setPreferredSize(new Dimension(ico.getIconWidth(), ico.getIconHeight()));
        favoriteButton.setFocusable(false);
        favoriteButton.setBorderPainted(false);
        favoriteButton.setBackground( new Color( 0, 0, 0, 0 ));
        favoriteButton.setOpaque(false);
        favoriteButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    rssFeedSetFavoriteButtonActionPerformed(evt);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog((Component)evt.getSource(),LabelStorage.ERROR_DESCRIPTION + ex.getMessage(), LabelStorage.ERROR_TITLE, JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        
        unsubscribeButton = new JButton(LabelStorage.UNSUBSCRIPTION_BUTTON_TEXT);
        unsubscribeButton.setToolTipText(LabelStorage.UNSUBSCRIPTION_BUTTON_TOOLTIP);
        unsubscribeButton.setBackground(new java.awt.Color(255, 255, 255));
        unsubscribeButton.setFont(new java.awt.Font("Tahoma", 1, 14));
        unsubscribeButton.setForeground(new java.awt.Color(0, 0, 0));
        unsubscribeButton.setFocusable(false);
        unsubscribeButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    rssFeedUnsubscribeButtonActionPerformed(evt);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog((Component)evt.getSource(),LabelStorage.ERROR_DESCRIPTION + ex.getMessage(), LabelStorage.ERROR_TITLE, JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(this);
        setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(container, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(unsubscribeButton)
                        .addComponent(favoriteButton)))
                .addContainerGap(0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(unsubscribeButton)
                    .addComponent(favoriteButton))
                .addComponent(container, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(0, Short.MAX_VALUE))
        );   
                
        addHyperlinkListener(new HyperlinkListener() {    
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
             if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                clickOnHyperlink(e.getURL());
             }   
            }
        
      });
        
      addMouseListener(new java.awt.event.MouseAdapter() {
          @Override
          public void mouseClicked(java.awt.event.MouseEvent evt) {
              rssFeed_Clicked(evt);
          }
      });
        
        htmlStyle = "<style>a {color: inherit; text-decoration: none} h2 { padding: 0; margin: 2px }</style>";
    }
    
    /**
     * RSSFeed-re kattintás kezelése
     * @param evt 
     */
    private void rssFeed_Clicked(java.awt.event.MouseEvent evt) {                                          
        panel.startProgress(LabelStorage.PROGRESS_TITLE_ON_LOADING);
        
        dailynewsreader.model.RSSFeed feed = panel.getFeed(this.title);
        panel.setRSSViewerContent(feed);
                    
        panel.endProgress();    
    }  
    
    /**
     * Leiratkozás gombra kattintás kezelése
     * @param evt
     * @throws Exception
     */
    private void rssFeedUnsubscribeButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
        panel.removeSubscription(title);
    }
    
    /**
     * Kedvencnek jelölő gombra kattintás kezelése
     * @param evt
     * @throws Exception 
     */
    private void rssFeedSetFavoriteButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
        panel.setFavorite(title);        
        setIsFavorite(!isFavorite);
    }
    
    /**
     * Hiperhivatkozásra kattintás kezelése
     * @param url Link url-je
     */
    private void clickOnHyperlink(URL url)
    {
        int option = JOptionPane.showConfirmDialog(this, "Megnyitja a böngészőben?", "Link", JOptionPane.YES_NO_OPTION);
                 
        if(Desktop.isDesktopSupported() && option == JOptionPane.YES_OPTION) {  
            try {
                Desktop.getDesktop().browse(url.toURI()); 
            } catch (Exception ex) {
                Logger.getLogger(RSSEntry.class.getName()).log(Level.SEVERE, null, ex);
            }   
        }
    }
    
    /**
     * Hiperlink eseményfigyelő
     * @param hyperlinkListener 
     */
    void addHyperlinkListener(HyperlinkListener hyperlinkListener) {
        container.addHyperlinkListener(hyperlinkListener);
    }
    
    /**
     * Tartalom beállítása, összeépítése
     */
     public void setContent(){        
        StringBuilder sb = new StringBuilder();
        sb.append(htmlStyle);        
        sb.append("<h2>" + this.title + "</h2>");       
        if (this.logoURL != null)
            sb.append(this.logoURL);
        container.setText(sb.toString());
    }
     
     /**
      * A feed logójának url címének beállítása
      * @param logoURL Logó url-je
      */
     public void setLogo(String logoURL){
         this.logoURL = logoURL;
     }    
}
